package com.idsmanager.zdh.web.validation.api;

import com.idsmanager.oauth.domain.security.Privilege;
import com.idsmanager.oauth.service.dto.user.UserRestTableDto;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import java.util.Set;

@Component
public class UserRestTableDtoValidator implements Validator {

    private final int usernameLength = 6;
    private final int passwordLength = 8;

    @Override
    public boolean supports(Class<?> clazz) {
        return UserRestTableDto.class.equals(clazz);
    }

    @Override
    public void validate(Object o, Errors errors) {
        UserRestTableDto userTableDto = (UserRestTableDto) o;

        validateUsername(userTableDto.getUsername(), errors);
        validatePassword(userTableDto.getPassword(), errors);
        validatePrivilege(userTableDto.getPrivileges(), errors);
    }

    private void validateUsername(String username, Errors errors) {
        if (StringUtils.isEmpty(username)) {
            errors.rejectValue(usernameField(), null, "username is required");
        } else {
            if (username.length() < usernameLength) {
                errors.rejectValue(usernameField(), null, "Username length must be >= 6");
            }
        }
    }

    private void validatePassword(String password, Errors errors) {
        if (StringUtils.isEmpty(password) ) {
            errors.rejectValue(passwordField(), null, "Password is required");
        } else {
            if (password.length() < passwordLength ) {
                errors.rejectValue(passwordField(), null, "Password length must be >= 8");
            }
        }
    }

    private void validatePrivilege(Set<Privilege> set, Errors errors) {
        if (set == null || set.size() < 0) {
            errors.rejectValue(privilegeField(), null, "privileges size must be >= 1");
        }
    }

    private String usernameField() {
        return "username";
    }

    private String passwordField() {
        return "password";
    }

    private String privilegeField() {
        return "privileges";
    }
}



